package cn.rengy.web.framework.sys.pub.classify;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import cn.rengy.lang.BusinessException;
import cn.rengy.tool.core.util._LongUtil;
import cn.rengy.web.framework.id.IdGenerator;
import cn.rengy.web.framework.sql.DbService;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class SysPubClassService {

	@Autowired
	private DbService dbService;
	
	@Autowired
	private IdGenerator idGenerator;
	
	@Transactional
	public void add(Map<String,Object> param) {
		Long id=idGenerator.nextId();
		String node_tree_id=_LongUtil.toString(id);
		Long parent_id=MapUtils.getLong(param, "parent_id");
		Long class_info_id=MapUtils.getLong(param, "class_info_id");
		String tree_id=null;
		String parent_tree_id="";
		if(parent_id==0){
			tree_id=node_tree_id;
		}else {
			parent_tree_id=this.dbService.querySingleColumn("select_pub_class_parent_tree_id", String.class, parent_id);
			tree_id=parent_tree_id.concat("-").concat(node_tree_id);
		}
		param.put("id",id);
		param.put("tree_id",tree_id);
		param.put("create_time", new Date());
		//1.更新排序号   like '%'相当于全部查询
		int maxSortNumber=this.dbService.querySingleColumn("select_pub_class_max_sort_number_by_tree_id", Long.class,class_info_id, parent_tree_id.concat("%")).intValue();
		this.dbService.update("update_pub_class_sort_number0", 1,class_info_id,maxSortNumber);
		//2.新增
		param.put("sort_number",maxSortNumber+1);
		this.dbService.updateMapParameter("insert_sys_pub_class", param);
		System.out.println(idGenerator.nowDate());
	}
	
	public void update(Map<String,Object> param) {
		//param.put("is_disabled", MapUtils.getIntValue(param, "is_disabled",1));
		this.dbService.updateMapParameter("update_sys_pub_class", param);
	}

	public void delete(Map<String,Object> param) {
		this.dbService.updateMapParameter("delete_sys_pub_class", param);
	}
	/**
	 * 单节点移动
	 * @param param
	 */
	@Transactional
	public void move(Map<String,Object> param) {
		Long move_node_id=MapUtils.getLong(param, "node");//待移动节点
		Long target_id=MapUtils.getLong(param, "target");//目标节点
		//"inner"：成为子节点，"prev"：成为同级前一个节点，"next"：成为同级后一个节点
		String moveType=MapUtils.getString(param, "moveType");
		Assert.notNull(moveType,"moveType must not be null");
		//移动和排序
		SysPubClassPO nodeClass=this.dbService.queryForBean("select_get_sys_pub_class", SysPubClassPO.class, move_node_id);
		Long class_info_id=nodeClass.getClass_info_id();
		//要移动的所有节点
		List<SysPubClassPO> moveList=this.dbService.queryForBeanList("select_sys_pub_class_by_tree_id", SysPubClassPO.class, nodeClass.getTree_id().concat("%"));
		//目标节点
		SysPubClassPO targetClass=null;
		String targetTreeId="";//目标节点tree_id
		if(target_id==0) {//根节点
			//虚拟根节点，数据库里不存在
			/*
			 * targetClass=new SysPubClassPO(); targetClass.setId(0L);
			 * targetClass.setTree_id("*"); targetClass.setSort_number(-1);
			 * targetClass.setParent_id(null);
			 */
		}else {
			targetClass=this.dbService.queryForBean("select_get_sys_pub_class", SysPubClassPO.class, target_id);
			targetTreeId=targetClass.getTree_id();
		}
		if(moveType.equals("inner")){
			//查询目标节点子节点最大sort_number，
			int maxSortNumber=this.dbService.querySingleColumn("select_pub_class_max_sort_number_by_tree_id", Long.class,class_info_id, targetTreeId.concat("%")).intValue();
			//1.先把目标节点后的所有节点序号更新为(子节点最大+移动节点数量)
			this.dbService.update("update_pub_class_sort_number0", moveList.size(),class_info_id,maxSortNumber);
			//2.移动到目标节点尾部
			for(int i=0,j=maxSortNumber;i<moveList.size();i++) {
				SysPubClassPO childNode=moveList.get(i);
				childNode.setSort_number(++j);
				if(i==0) {
					childNode.setParent_id(target_id);
					if(targetTreeId.length()==0) {
						childNode.setTree_id(_LongUtil.toString(childNode.getId()));
					}else {
						childNode.setTree_id(targetTreeId.concat("-").concat(_LongUtil.toString(childNode.getId())));
					}
				}else {
					SysPubClassPO preNode=moveList.get(i-1);
					if(childNode.getParent_id().equals(preNode.getId())) {//当前节点是pre的子节点
						childNode.setTree_id(preNode.getTree_id().concat("-").concat(_LongUtil.toString(childNode.getId())));
					}else if(childNode.getParent_id().equals(preNode.getParent_id())){//同级节点
						String parentTreeId=preNode.getTree_id().substring(0,preNode.getTree_id().lastIndexOf("-"));
						childNode.setTree_id(parentTreeId.concat("-").concat(_LongUtil.toString(childNode.getId())));
					}else {
						log.error("树形节点数据排序错误");
						throw new BusinessException("系统错误");
					}
				}
			}
		}else if(moveType.equals("prev")) {
			if(target_id==0) {
				throw new IllegalArgumentException("不能移动到根节点的同级节点,只能有一个根节点");
			}
			/**
			 * 父节点是target的父节点
			 * 把target节点和之后的节点sort_number+移动节点数量
			 * 
			 * */
			this.dbService.update("update_pub_class_sort_number_pre", moveList.size(),class_info_id,targetClass.getSort_number());
			//2.移动
			for(int i=0,j=targetClass.getSort_number();i<moveList.size();i++) {
				SysPubClassPO childNode=moveList.get(i);
				childNode.setSort_number(j++);
				if(i==0) {
					//和目标节点是同级节点
					childNode.setParent_id(targetClass.getParent_id());
					if(targetClass.getParent_id()==0) {
						childNode.setTree_id(_LongUtil.toString(childNode.getId()));
					}else {
						//取得同级节点的父tree_id
						String parentTreeId=targetClass.getTree_id().substring(0,targetClass.getTree_id().lastIndexOf("-"));
						childNode.setTree_id(parentTreeId.concat("-").concat(_LongUtil.toString(childNode.getId())));
					}
				}else {
					SysPubClassPO preNode=moveList.get(i-1);
					if(childNode.getParent_id().equals(preNode.getId())) {//当前节点是pre的子节点
						childNode.setTree_id(preNode.getTree_id().concat("-").concat(_LongUtil.toString(childNode.getId())));
					}else if(childNode.getParent_id().equals(preNode.getParent_id())){//同级节点
						String parentTreeId=preNode.getTree_id().substring(0,preNode.getTree_id().lastIndexOf("-"));
						childNode.setTree_id(parentTreeId.concat("-").concat(_LongUtil.toString(childNode.getId())));
					}else {
						log.error("树形节点数据排序错误");
						throw new BusinessException("系统错误");
					}
				}
			}
		}else if(moveType.equals("next")) {
			if(target_id==0) {
				throw new IllegalArgumentException("不能移动到根节点的同级节点,只能有一个根节点");
			}
			/**
			 * 父节点是target的父节点
			 * 把target之后的节点sort_number+移动节点数量
			 * 
			 * */
			//查询目标节点子节点最大sort_number，
			int maxSortNumber=this.dbService.querySingleColumn("select_pub_class_max_sort_number_by_tree_id", Long.class,class_info_id, targetTreeId.concat("%")).intValue();
			//1.先把目标节点后的所有节点序号更新为(子节点最大+移动节点数量)
			this.dbService.update("update_pub_class_sort_number0", moveList.size(),class_info_id,maxSortNumber);
			//2.移动
			for(int i=0,j=maxSortNumber;i<moveList.size();i++) {
				SysPubClassPO childNode=moveList.get(i);
				childNode.setSort_number(++j);
				if(i==0){
					//和目标节点是同级节点
					childNode.setParent_id(targetClass.getParent_id());
					if(targetClass.getParent_id()==0) {
						childNode.setTree_id(_LongUtil.toString(childNode.getId()));
					}else {
						//取得同级节点的父tree_id
						String parentTreeId=targetClass.getTree_id().substring(0,targetClass.getTree_id().lastIndexOf("-"));
						childNode.setTree_id(parentTreeId.concat("-").concat(_LongUtil.toString(childNode.getId())));
					}
				}else{
					SysPubClassPO preNode=moveList.get(i-1);
					if(childNode.getParent_id().equals(preNode.getId())) {//当前节点是pre的子节点
						childNode.setTree_id(preNode.getTree_id().concat("-").concat(_LongUtil.toString(childNode.getId())));
					}else if(childNode.getParent_id().equals(preNode.getParent_id())){//同级节点
						String parentTreeId=preNode.getTree_id().substring(0,preNode.getTree_id().lastIndexOf("-"));
						childNode.setTree_id(parentTreeId.concat("-").concat(_LongUtil.toString(childNode.getId())));
					}else {
						log.error("树形节点数据排序错误");
						throw new BusinessException("系统错误");
					}
				}
			}
		}
		this.dbService.batchUpdateBeanParameter("update_pub_class_move", moveList);
	}
}
